<template>
    <div class="article-detail-container">
        <div class="back-button" @click="router.back()">
            <van-icon name="arrow-left" size="28" />
        </div>

        <div class="detail-wrapper">
            <el-carousel v-if="coverImages.length" height="60vh" indicator-position="outside">
                <el-carousel-item v-for="(img, index) in coverImages" :key="index">
                    <el-image :src="img" fit="cover" class="cover-image" :preview-src-list="coverImages" />
                </el-carousel-item>
            </el-carousel>

            <div class="content-wrapper">
                <h1 class="title">{{ article.title }}</h1>

                <div class="meta-info">
                    <div class="author-info">
                        <el-avatar :src="userInfo.userPic" />
                        <span class="username">{{ userInfo.username }}</span>
                    </div>
                    <div class="stats">
                        <span class="stat-item">
                            <van-icon name="like" color="#ee0a24" />
                            {{ article.likes || 0 }}
                        </span>
                        <span class="publish-time">
                            {{ formatTime(article.createTime) }}
                        </span>
                    </div>
                </div>

                <div class="article-content" v-html="processedContent" />

                <div class="interaction-area">
                    <el-button :type="interactionState.isLiked ? 'danger' : 'default'"
                        :loading="interactionState.likeLoading" round @click="handleLike">
                        <van-icon :name="interactionState.isLiked ? 'like' : 'like-o'"
                            :color="interactionState.isLiked ? '#fff' : '#666'" />
                        {{ interactionState.isLiked ? '已点赞' : '点赞' }}
                    </el-button>

                    <el-button :type="interactionState.isCollected ? 'warning' : 'default'"
                        :loading="interactionState.collectLoading" round @click="handleCollect">
                        <van-icon :name="interactionState.isCollected ? 'star' : 'star-o'"
                            :color="interactionState.isCollected ? '#fff' : '#666'" />
                        {{ interactionState.isCollected ? '已收藏' : '收藏' }}
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Icon as VanIcon } from 'vant'
import { ElMessage } from 'element-plus'
import { getArticleDetail } from '../api/article'
import { interactApi } from '../api/article'
import { getUserInfo } from '../api/user'
import { useUserStore } from '../stores/user'
import type { ArticleItem } from '../types/article'
import type { MinimalUser } from '../types/user'
import DOMPurify from 'dompurify'   // 安全处理，防止XSS攻击

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
// 用户信息响应式对象
const userInfo = ref<MinimalUser>({
    id: 0,
    username: '加载中...',
    userPic: 'https://api.multiavatar.com/default.png'
})

// 文章数据
const article = ref<ArticleItem>({
    id: 0,
    title: '',
    content: '',
    coverImg: '',
    state: '',
    categoryId: 0,
    createUser: 0,
    createTime: '',
    updateTime: '',
    likes: 0,
    comments: 0
})

// 互动状态
const interactionState = ref({
    isLiked: false,
    isCollected: false,
    likeLoading: false,
    collectLoading: false
})

// 定时器引用
let loveTimer: ReturnType<typeof setInterval> | null = null

// 封面图片处理
const coverImages = computed(() => {
    return article.value.coverImg ? [article.value.coverImg] : []
})

// 时间格式化
const formatTime = (timeStr: string) => {
    return new Date(timeStr).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 获取文章详情
const fetchArticle = async () => {
    try {
        const res = await getArticleDetail(Number(route.params.id))
        if (res.data.code === 1) {
            article.value = {
                ...res.data.data,
                likes: res.data.data.likes ?? 0,
                comments: res.data.data.comments ?? 0
            }

            // 新增用户信息获取
            try {
                const userRes = await getUserInfo(article.value.createUser.toString())
                if (userRes.data.code === 1) {
                    userInfo.value = {
                        id: userRes.data.data.id,
                        username: userRes.data.data.nickname || `用户${article.value.createUser}`,
                        userPic: userRes.data.data.userPic
                            ? userRes.data.data.userPic
                            : `https://api.multiavatar.com/${article.value.createUser}.png`
                    }
                }
            } catch (userErr) {
                console.error('用户信息获取失败:', userErr)
                userInfo.value = {
                    id: article.value.createUser,
                    username: `用户${article.value.createUser}`,
                    userPic: `https://api.multiavatar.com/${article.value.createUser}.png`
                }
            }

            // 原有互动状态初始化
            interactionState.value.isLiked = false // 实际应根据接口数据
            interactionState.value.isCollected = false
        }
    } catch (err) {
        ElMessage.error('文章加载失败')
        router.back()
    }
}

// 点赞处理
const handleLike = async () => {
    if (!userStore.isLoggedIn) return ElMessage.warning('请先登录')

    try {
        interactionState.value.likeLoading = true
        if (interactionState.value.isLiked) {
            await interactApi.unlike(article.value.id)
            article.value.likes = (article.value.likes || 0) - 1
        } else {
            await interactApi.like(article.value.id)
            article.value.likes = (article.value.likes || 0) + 1
        }
        interactionState.value.isLiked = !interactionState.value.isLiked
    } catch (error) {
        ElMessage.error('操作失败，请重试')
    } finally {
        interactionState.value.likeLoading = false
    }
}

// 收藏处理
const handleCollect = async () => {
    if (!userStore.isLoggedIn) return ElMessage.warning('请先登录')

    try {
        interactionState.value.collectLoading = true
        if (interactionState.value.isCollected) {
            await interactApi.uncollect(article.value.id)
        } else {
            await interactApi.collect(article.value.id)
        }
        interactionState.value.isCollected = !interactionState.value.isCollected
        ElMessage.success(interactionState.value.isCollected ? '收藏成功' : '已取消收藏')
    } catch (error) {
        ElMessage.error('操作失败，请重试')
    } finally {
        interactionState.value.collectLoading = false
    }
}

// 初始化定时器
const startLoveTimer = () => {
    loveTimer = setInterval(async () => {
        try {
            await interactApi.addLoveStatistic(article.value.id)
        } catch (error) {
            console.error('统计发送失败:', error)
        }
    }, 10000)
}

// 增加图片链接转换函数
const convertImageLinks = (html: string) => {
    // 匹配图片链接并替换为img标签
    const imgLinkRegex = /<a\s+(?:[^>]*?\s+)?href="(https?:\/\/[^"]+\.(?:jpeg|jpg|png|gif))"[^>]*>(?:https?:\/\/[^"]+\.(?:jpeg|jpg|png|gif))<\/a>/gi
    return html.replace(imgLinkRegex, (_, url) => {
        return `<img src="${url}" alt="文章图片" class="content-image">`
    })
}

// 安全处理后的内容计算属性
const processedContent = computed(() => {
    let content = article.value.content
    // 转换图片链接
    content = convertImageLinks(content)
    // 安全过滤
    return DOMPurify.sanitize(content, {
        ALLOWED_TAGS: ['p', 'strong', 'span', 'br', 'img'], // 允许图片标签
        ALLOWED_ATTR: ['style', 'src', 'alt', 'class'] // 允许图片属性
    })
})

// 生命周期
onMounted(() => {
    fetchArticle()
    startLoveTimer()
})

onUnmounted(() => {
    loveTimer && clearInterval(loveTimer)
})
</script>

<style lang="less" scoped>
.article-detail-container {
    position: relative;
    max-width: 1200px;
    margin: 0 auto;
    padding: 40px 20px;

    .back-button {
        position: absolute;
        left: -40px;
        top: 20px;
        cursor: pointer;
        color: #666;
        transition: color 0.3s;

        &:hover {
            color: #eb4d4b;
        }
    }

    .detail-wrapper {
        background: white;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        overflow: hidden;

        .cover-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .content-wrapper {
            padding: 32px;

            .title {
                font-size: 32px;
                margin-bottom: 24px;
                color: #333;
                line-height: 1.4;
            }

            .meta-info {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 32px;
                padding-bottom: 24px;
                border-bottom: 1px solid #eee;

                .author-info {
                    display: flex;
                    align-items: center;
                    gap: 12px;

                    .username {
                        font-size: 16px;
                        color: #666;
                    }
                }

                .stats {
                    display: flex;
                    align-items: center;
                    gap: 24px;
                    color: #999;

                    .stat-item {
                        display: flex;
                        align-items: center;
                        gap: 6px;

                        .van-icon {
                            font-size: 18px;
                        }
                    }
                }
            }

            .article-content {
                line-height: 1.8;
                font-size: 16px;
                color: #333;

                :deep(img) {
                    max-width: 100%;
                    height: auto;
                    margin: 20px 0;
                    border-radius: 8px;
                }

                :deep(a) {
                    color: #eb4d4b;
                    text-decoration: underline;
                }

                :deep(img.content-image) {
                    max-width: 100%;
                    height: auto;
                    margin: 1em 0;
                    border-radius: 8px;
                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                    display: block;
                    margin-left: auto;
                    margin-right: auto;
                }
            }

            .interaction-area {
                margin: 40px 0;
                display: flex;
                gap: 16px;

                .el-button {
                    display: inline-flex;
                    align-items: center;
                    padding: 12px 24px;

                    .van-icon {
                        font-size: 20px;
                        margin-right: 6px;
                    }
                }
            }
        }
    }
}

// Vant 图标全局调整
.van-icon {
    vertical-align: middle;
}

@media (max-width: 768px) {
    .article-detail-container {
        padding: 20px;

        .back-button {
            left: 10px;
            top: 10px;
        }

        .detail-wrapper {
            .content-wrapper {
                padding: 20px;

                .title {
                    font-size: 24px;
                }

                .meta-info {
                    flex-direction: column;
                    align-items: flex-start;
                    gap: 16px;
                }

                .interaction-area {
                    .el-button {
                        padding: 10px 20px;
                    }
                }
            }
        }
    }
}
</style>